package com.springboot.utils;

import org.springframework.beans.BeanUtils;
import org.springframework.beans.BeanWrapper;
import org.springframework.beans.BeanWrapperImpl;

import java.beans.PropertyDescriptor;
import java.util.HashSet;
import java.util.Set;

/***
 *@descrition: 对象复制工具类
 *@date: 2020/5/21
 * @author: lzh
 */
public class CopyObjectUtil {

    /**
     * @descrition:
     * @param s : sourceObject
     * @param r : targetObject
     * @return : R
     */
    public static <S, T> void copyNotNull(S s, T t) {
        BeanWrapper src = new BeanWrapperImpl(s);
        PropertyDescriptor[] pds = src.getPropertyDescriptors();
        Set<String> emptyNames = new HashSet<>();
        for (PropertyDescriptor pd : pds) {
            Object srcValue = src.getPropertyValue(pd.getName());
            if (srcValue == null) {
                emptyNames.add(pd.getName());
            }
        }
        String[] strings = emptyNames.toArray(new String[emptyNames.size()]);
        BeanUtils.copyProperties(s, t, strings);
    }
}
